package com.yaodian100.mall.member.web;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.ec.member.entity.LoginHistory;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.mall.member.util.UserData;

/**
 * 
 * @author apple.chang
 * 
 */
public class TrustMemberAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8576295992782217164L;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private static final String KAIXIN_MEMBER = "kaixinmember";
	private static final String KAIXIN_ID = "@kaixin";
	private static final String KAIXIN_COOKIE_NAME = "kx_connect_session_key";

	@Resource
	private CartOrdersService cartOrdersService;
	private MemberService memberService;

	private Member member;
	private String loginId;
	private String result;

	public String kaixinLogin() throws CoreException, Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		loginId = userData.readRawValue(KAIXIN_COOKIE_NAME);
		if (StringUtils.isBlank(loginId)) {
			result = "error";
			return "jsonLoginOK";
		}
		loginId = loginId.split("_")[0];
		member = memberService.getMemberByLoginId(loginId + KAIXIN_ID);
		if (null == member) {
			member = new Member();
			member.setLoginId(loginId + KAIXIN_ID);
			member.setPwd("xx");
			member.setEmail("xx");
			member.setRank("1");
			member.setStatus("00");
			member.setActiveDate(new Date());

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			member.setApplySource(KAIXIN_MEMBER);
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.save(member);
			memberService.newBalance(member);
			// MemberEvent me = memberService.checkMemberEvent(member);
			// if (null != me) {
			// pathparam = "http://" + request.getServerName() + ServerValue.getFrontContextPath() + "/member/"
			// + ("2".equals(me.getType()) ? "myBonus/tomybonus.do" : "myCoupon/tomycoupon.do");
			// }
		}
		autoLogin(memberService.getMemberByLoginId(member.getLoginId()), null);
		result = "loginOK";
		return "jsonLoginOK";
	}

	private void autoLogin(Member member, String showName) throws Exception {
		if (null != member) {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			// get ip
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);

			UserData userData = new UserData(request, response);
			userData.clearAll();
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());
			if (StringUtils.isNotBlank(showName)) {
				userData.setShowName(showName);
			}

			memberService.checkBalance(member);
			LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
			if (null != loginHistory) {
				member.setLastLoginTime(loginHistory.getLoginTime());
				memberService.update(member);
				memberService.deleteLoginHistory(member.getLoginId());
			}

			memberService.saveFrontendLoginHistory(member, clientIp);
			memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());

			CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
			if (cartOrders == null) {
				cartOrders = cartOrdersService.createCart(member.getMemberId(), null, null, null, 0, null, null);
			}
			String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

			cartOrders = processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);

			// 记录购物车商品数量
			cartOrders = cartOrdersService.get(cartOrders.getCartId());
			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		}
	}

	private CartOrders processMoveTmpCartToCartOrder(String tmpCartid, String memberCartId,
			CartOrdersService cartordersService, UserData userData) throws Exception {
		// 若memberCartId為空，則新增一個cartOrders
		// logger.info("memberCartId:{}", memberCartId);
		CartOrders cartOrders = null;
		if (memberCartId == null) {
			cartOrders = cartordersService.createCart(userData.getMemberId(), null, null, null, 0, null, null);
			memberCartId = cartOrders.getCartId();
			userData.writeRawValue("cartid", cartOrders.getCartId());
			// memberCartId = createNewCartOrders(memberCartId, userData);
		} else {
			cartOrders = cartordersService.getCart(memberCartId, null);
		}
		// logger.info("cartOrders:{}", cartOrders);
		if (StringUtils.isNotBlank(tmpCartid)) {
			CartOrders tmpCart = cartordersService.get(tmpCartid);
			if (null != tmpCart) {
				boolean hasTempQP = false;
				// 检查暂存购物车内是否有满额购，若有，移除会员购物车内之满额购
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {
					if (cop.getProdTp().equals(Product.PRODUCT_TYPE.QUOTAFILLED.getValue())) {
						// 若有满额购
						hasTempQP = true;
					}
				}
				if (hasTempQP) {
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (memberCop.getProdTp().equals(Product.PRODUCT_TYPE.QUOTAFILLED.getValue())) {
							cartOrders.getCartOrderProducts().remove(memberCop);
							break;
						}
					}
				}

				// 將暫存的車移至cartOrderProduct
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {

					boolean isItemExists = false;
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (cop.getProdId().equals(memberCop.getProdId()) && cop.getProdSpecId().equals(memberCop.getProdSpecId())) {
							isItemExists = true;
							break;
						}
					}
					if (!isItemExists) {
						CartOrderProduct tmpcop = new CartOrderProduct();
						// tmpcop.setAmount(new BigDecimal(0.00));
						BeanUtils.copyProperties(cop, tmpcop, new String[] { "cartOrderProdId", "cartOrder", "coupon",
								"modifyDate", "details" });
						// logger.info("tmpcop:{}", tmpcop.getAmount());
						cartOrders.addCartOrderProduct(tmpcop);
						for (CartOrderProductDetail detail : cop.getDetails()) {
							CartOrderProductDetail cloneDetail = new CartOrderProductDetail();
							BeanUtils.copyProperties(detail, cloneDetail, new String[] { "cartOrderDetailId", "cartOrderProdId",
									"orderProduct", "cartId", "cartOrder", "modifyDate", "details" });
							tmpcop.addDetail(cloneDetail);

						}
					}
				}
				// 刪除暫存車的cartOrders
				cartOrders = cartordersService.save(cartOrders);
				cartordersService.delete(tmpCart);
			}
		}
		return cartOrders;
	}

	public String getLoginId() {
		return loginId;
	}

	public void setLoginId(String loginId) {
		this.loginId = loginId;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
}